package protocol;

import java.net.Socket;
import java.net.UnknownHostException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class CommSckClient implements Runnable {
	private Socket sckt = null;
	private ObjectInputStream is = null;
	private ObjectOutputStream os = null;
	private String address;
	private int port;
	private Thread thread;
	private CommandRelay cmdRly;
	
	public CommSckClient(CommandRelay cmdRly) {
		this("127.0.0.1",11168, cmdRly);
	}
	public CommSckClient(String address, int port, CommandRelay cmdRly) {
		this.address = address;
		this.port = port;		
		this.cmdRly = cmdRly;
		thread = new Thread(this);
		thread.start();
	}

	public void run() {
		System.out.println("sckt: run()");
		try {
			sckt = new Socket(address, port);
			System.out.println("sckt: Connected!");
			os = new ObjectOutputStream(sckt.getOutputStream());
			System.out.println("sckt: outputstream open!");
			is = new ObjectInputStream(sckt.getInputStream());
			while(!sckt.isClosed()) {
				// stuur een opdracht
				System.out.println("sckt: getCommand(): ");
				Cmd cmnd = cmdRly.getOutCmd();
				
				if (cmnd != null) {
					os.writeObject(cmnd/*cmdRly.getOutCmd()*/);
					System.out.println("Client Outcommand: " + cmnd.getCommand() + " "  + cmnd.getAgvNummer() + " " + cmnd.getKraannr());
				}					
			
				// krijg info terug
				System.out.println("sckt: setCommand()");
				try {
					System.out.println("Serv: Available: " +is.available());
					if (is.available() != 0) {
						Cmd cmd = (Cmd)is.readObject();
						cmdRly.addInCmd(/*(Cmd)is.readObject()*/cmd);
						System.out.println("Client: Incommand: " + cmd.getCommand() + " "  + cmd.getAgvNummer() + " " + cmd.getKraannr());
					}
				} catch (ClassNotFoundException e) {
					e.printStackTrace();
				}
			}
		}
		catch (UnknownHostException uhe) {
			uhe.printStackTrace();
		}
		catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}
}
